import { NextApiRequest, NextApiResponse } from 'next'
import {withIronSessionApiRoute} from 'iron-session/next'
import {prepareConnection} from 'db/index'
import { User,Article,Comment} from 'db/entity/index'
import {ironOptions} from 'config/index'
import { ISession} from 'pages/api/index'
import { EXCEPTION_COMMENT } from 'pages/api/config/codes'

export default withIronSessionApiRoute(publish,ironOptions)

async function publish(req: NextApiRequest, res: NextApiResponse) {
    const sesssion: ISession = req.session
    const {articleId=0,content=''} = req.body
    // 连接数据库
    const db = await prepareConnection()
    const articleRepo = db.getRepository(Article)
    const userRepo = db.getRepository(User)
    const commentRepo = db.getRepository(Comment)
    // 判断用户是否登录，未登录则返回错误
    const user = await userRepo.findOne({id: sesssion?.userId})
    const article = await articleRepo.findOne({id:articleId})
    // 操作数据库，写入数据
    const comment = new Comment()
    comment.content = content
    comment.create_time = new Date()
    comment.update_time = new Date()
    // 判断用户是否存在，存在则将数据关联到用户
    if(user){
        comment.user = user
    }
    if(article){
        comment.article = article
    }

    console.log(comment)
    // 保存数据
    const resComment = await commentRepo.save(comment)
    console.log('resComment',resComment)
    if(resComment){
        // 返回数据
        res?.status(200).json({code:0,msg:'发布成功',data:resComment})
    }else{
        // 返回错误
        res?.status(200).json({...EXCEPTION_COMMENT.PUBLISH_FAILED})
    }
}